import * as types from "../types/serviceInfoTypes";
import NetWorkUtil from "../utils/NetWorkUtil";
import ApiConstants from "../common/ApiConstants";

export function getServiceInfo(serviceItem) {
  return dispatch => {
    dispatch({ type: types.SERVICEINFO_CHANGEDEVICEMODEL, serviceItem });
    const { facility_id, service_id } = serviceItem;
    NetWorkUtil.getWithoutLogin(ApiConstants.DEVICEMODEL_SERVICEINFO, { facility_id, service_id })
      .then(res => {
        const imageList = [];
        for (let i = 0; i < res.length; i += 1) {
          const detail = res[i].service_detail;
          const matches = detail.match(/src=".*?"/gi);
          if (matches !== null) {
            for (let j = 0; j < matches.length; j += 1) {
              const arr = matches[j].split(/^src="(.+)?"/gi);
              if (arr !== null && imageList.indexOf(arr[1]) === -1) {
                imageList.push(arr[1]);
              }
            }
          }
        }
        dispatch({ type: types.SERVICEINFO_DONE, serviceInfo: res, imageList });
      })
      .catch(error => {
        dispatch({ type: types.SERVICEINFO_ERROR, error });
      });
  };
}

export function init(serviceItem) {
  return dispatch => {
    const { service_id } = serviceItem;
    dispatch({ type: types.SERVICEINFO_INITING, serviceId: service_id });
    dispatch(getServiceInfo(serviceItem));
  };
}

export function changeServiceWay(newIndex) {
  return dispatch => {
    dispatch({ type: types.SERVICEINFO_CHANGESERVICEWAY, curServiceWayIndex: newIndex });
  };
}

export function serviceInfoUnmount() {
  return dispatch => {
    dispatch({ type: types.SERVICEINFO_SERVICEINFOUNMOUNT });
  };
}

export function serviceInfoChangeDeviceModel(serviceItem, serviceId) {
  return dispatch => {
    serviceItem.service_id = serviceId;
    dispatch(getServiceInfo(serviceItem));
  };
}
